package com.chain.BrotherExchange.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.event.LogoutEvent;
import com.chain.BrotherExchange.event.SubmitLevel2CertificationEvent;
import com.chain.BrotherExchange.event.SubmitRealNameAuthenticationEvent;
import com.chain.BrotherExchange.event.UserNicknameChangeEvent;
import com.chain.BrotherExchange.event.UserPortraitChangeEvent;
import com.chain.BrotherExchange.ui.core.AbsNetworkStateActivity;
import com.chain.BrotherExchange.utils.ActivityBarHelper;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.utils.ImageViews;
import com.chain.BrotherExchange.viewmodel.IDAuthenticationViewModel;
import com.chain.BrotherExchange.viewmodel.PersonalCenterViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.example.common.widget.state.NetworkStateLayout;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.Bind;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 个人中心
 */
public class PersonalCenterActivity extends AbsNetworkStateActivity implements EasyPermissions.PermissionCallbacks {

    @Bind(R.id.logout_button) Button mLogoutButton;
    @Bind(R.id.auth_entry_image) View mAuthEntryImage;
    @Bind(R.id.avatar_image_view) ImageView mAvatarImageView;
    @Bind(R.id.nickname_text_view) TextView mNicknameTextView;
    @Bind(R.id.change_nickname_layout) View mChangeNicknameLayout;
    @Bind(R.id.real_name_authentication_layout) View mRealNameAuthenticationLayout;
    @Bind(R.id.authentication_network_state_layout) NetworkStateLayout mNetworkStateLayout;
    @Bind(R.id.authentication_state_text_view) TextView mRealNameAuthSateText;
    @Bind(R.id.modify_picture_layout) View mModifyPictureLayout;
    @Bind(R.id.level_2_auth_entry_image) View mLevel2AuthEntryView;
    @Bind(R.id.level_2_certification_layout) View mLevel2CertificationLayout;
    @Bind(R.id.level_2_certification_text_view) TextView mLevel2CertificationTextView;

    private PersonalCenterViewModel mViewModel;
    private IDAuthenticationViewModel mAuthenticationViewModel;

    public static void launch(Context context) {
        context.startActivity(new Intent(context, PersonalCenterActivity.class));
    }

    @Override
    public int getTitleLayoutRes() {
        return R.layout.layout_default_title_bar;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_personal_center;
    }

    @Override
    protected void initActions() {
        mViewModel = ViewModelProviders.of(this).get(PersonalCenterViewModel.class);
        mAuthenticationViewModel = ViewModelProviders.of(this).get(IDAuthenticationViewModel.class);

        // 用户信息
        initUserInfo();

        // 认证信息
        initAuthenticationInfo();
        mNetworkStateLayout.setOnAnewRequestNetworkListener(this::initAuthenticationInfo);

        // 标题
        ActivityBarHelper.init(this, R.string.title_personal_center);

        // 修改昵称
        mChangeNicknameLayout.setOnClickListener(v ->
                ModifyNicknameActivity.launch(v.getContext(), mNicknameTextView.getText().toString())
        );

        // 退出登录
        mLogoutButton.setOnClickListener(v -> logout());

        // 选择头像
        mModifyPictureLayout.setOnClickListener(v -> requestPermission());
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    private void selectPortrait() {
        Matisse.from(PersonalCenterActivity.this)
                .choose(MimeType.allOf())
                .countable(true)
                .maxSelectable(1)
                .theme(R.style.Matisse_UNT)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(C.REQ_CHOOSE);
    }

    private void initAuthenticationInfo() {
        mAuthenticationViewModel.isAuthentication().observe(this, resource -> {
            Resource.load(this, resource, mNetworkStateLayout, result -> {
                mRealNameAuthSateText.setText(result.getRealNameAuthenticationText());
                mLevel2CertificationTextView.setText(result.getLevel2CertificationText());
                int check_mark_first = result.getCheck_mark_first();
                if (check_mark_first == C.API_UNAUTHORIZED || check_mark_first == C.API_AUTHENTICATION_FAILURE) {
                    mAuthEntryImage.setVisibility(View.VISIBLE);
                    EventBus.getDefault().post(new SubmitRealNameAuthenticationEvent(C.API_AUTHENTICATION_SUCCESS));
                    mRealNameAuthenticationLayout.setOnClickListener(v ->
                            RealNameAuthenticationActivity.launch(v.getContext()));
                }

                int check_mark_second = result.getCheck_mark_second();
                if (check_mark_second == C.API_UNAUTHORIZED || check_mark_second == C.API_AUTHENTICATION_FAILURE) {
                    mLevel2AuthEntryView.setVisibility(View.VISIBLE);
                    mLevel2CertificationLayout.setOnClickListener(v ->
                            Level2CertificationActivity.launch(v.getContext()));
                }
            });
        });
    }

    private void initUserInfo() {
        mViewModel.userInfo().observe(this, resource -> {
            Resource.load(this, resource, this, result -> {
                ImageViews.load(result.getHead_scul(), mAvatarImageView);
                mNicknameTextView.setText(result.getNick_name());
            });
        });
    }

    private void logout() {
        new AlertDialog.Builder(this)
                .setMessage(R.string.message_exit_the_app)
                .setPositiveButton(R.string.sure, (dialog, which) -> {
                    Androids.LocalConfig.logout();
                    EventBus.getDefault().post(new LogoutEvent());
                    MainActivity.launch(this);
                }).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()
        ).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            selectPortrait();
        } else if (requestCode == C.REQ_CHOOSE && resultCode == RESULT_OK) {
            Uri uri = Matisse.obtainResult(data).get(0);
            mAvatarImageView.setImageURI(uri);

            // 上传头像
            submitNewPortrait(uri);
        }
    }

    private void submitNewPortrait(Uri uri) {
        mViewModel.modifyPortrait(mAvatarImageView).observe(this, resource -> {
            if (resource.state == Resource.Status.LOADING) {
                Androids.showProgressMessage(this, R.string.uploading_avatar);
            } else {
                Androids.dismissProgressMessage();
                Androids.makeText(resource.source);
                if (resource.state == Resource.Status.SUCCESS) {
                    EventBus.getDefault().post(new UserPortraitChangeEvent(uri));
                }
            }
        });
    }

    private void requestPermission() {
        String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, permissions)) {
            String rationale = getString(R.string.please_approve_camera_permissions);
            EasyPermissions.requestPermissions(this, rationale, 0, permissions);
        } else {
            selectPortrait();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        selectPortrait();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(R.string.auto_authorization_failure)
                    .setRationale(R.string.please_manually_select_approve_camera_permissions).build().show();
        } else {
            Androids.makeText(R.string.authorization_failure);
        }
    }

    @Subscribe
    public void userNicknameChange(UserNicknameChangeEvent event) {
        mNicknameTextView.setText(event.nickname);
    }

    @Subscribe
    public void realNameAuthentication(SubmitRealNameAuthenticationEvent event){
        mRealNameAuthSateText.setText(R.string.in_authentication);
        mLevel2AuthEntryView.setVisibility(View.GONE);
        mRealNameAuthenticationLayout.setOnClickListener(null);
    }

    @Subscribe
    public void level2Certification(SubmitLevel2CertificationEvent event){
        mLevel2CertificationTextView.setText(R.string.in_authentication);
        mLevel2AuthEntryView.setVisibility(View.GONE);
        mLevel2CertificationLayout.setOnClickListener(null);
    }

    @Override
    public void onAnewRequest() {
        initUserInfo();
    }
}
